package cn.feuler.code8081.service;

import cn.feuler.code8081.mapper.AuthCodeMapper;
import cn.feuler.common.entity.AuthCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Service
public class AuthCodeService {

    private final AuthCodeMapper authCodeMapper;

    public AuthCodeService(AuthCodeMapper authCodeMapper) {
        this.authCodeMapper = authCodeMapper;
    }

    public AuthCode create(String email) {
        AuthCode exists = authCodeMapper.selectOne(new QueryWrapper<AuthCode>().eq("email", email));
        if (exists != null) {
            if (exists.getExpireTime().isAfter(LocalDateTime.now())) {
                return exists;
            } else {
                authCodeMapper.deleteById(exists.getId());
            }
        }
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(RandomStringUtils.randomAlphanumeric(4));
        authCode.setCreateTime(LocalDateTime.now());
        authCode.setExpireTime(LocalDateTime.now().plus(1, ChronoUnit.MINUTES));
        authCodeMapper.insert(authCode);
        return authCode;
    }

    public Integer validate(String email, String code) {
        AuthCode exists = authCodeMapper.selectOne(new QueryWrapper<AuthCode>().eq("email", email));
        if (exists == null || !exists.getCode().equals(code)) {
            return 1;
        }
        return exists.getExpireTime().isBefore(LocalDateTime.now()) ? 2 : 0;
    }
}
